﻿using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.FromBody.GsDataModel;
using CoreShop.PrintService;
using CoreShop.Services;
using Loading;
using MySqlX.XDevAPI.Common;
using NAudio.Gui;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using Yitter.IdGenerator;
using static CoreShop.Library.GlobalEnumVars;

namespace CoreShop.App
{
    public partial class frmCreditsExchange : UIForm
    {
        OpaqueCommand cmd = new OpaqueCommand();
        private corecmsuser member = null;
        public bool sSelectFlag = false;
        public decimal allCouponAmount = 0;
        public List<CreditsExchangeModel> creditsExchangeList = new List<CreditsExchangeModel>();
        public CreditsExchangeModel creditsExchangeInfo = null;
        public int creditsExchangeType = (int)GlobalEnumVars.CreditsExchangeType.Goods;

        public frmCreditsExchange(corecmsuser _member,int _creditsExchangeType)
        {
            InitializeComponent();
            this.member = _member;
            this.creditsExchangeType = _creditsExchangeType;
        }

        private async void frmfoodfeed_Load(object sender, System.EventArgs e)
        {
            string msg = "";
            lblMemberName.Text = "会员电话：" + member.mobile;
            lbl_points.Text = member.point.ToString();
            var orderCoupon = new OrderCouponPost();
            orderCoupon.storeId = AppConstVars.sysUser.storeId;
            orderCoupon.couponCode = "";
            orderCoupon.userId = member.id;
            orderCoupon.wxUserId = 0;
            orderCoupon.channel = 1;
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                creditsExchangeList = await MemberApiUtil.GetIntegralGoodsList(AppConstVars.sysUser);
                if ((creditsExchangeList != null) && (creditsExchangeList.Count > 0))
                {
                    int index = 1;
                    foreach (var creditsExchange in creditsExchangeList)
                    {
                        //if (!CheckCouponGoods(couponBatchId, vipCoupon)) continue;
                        if (creditsExchange.type != creditsExchangeType) continue;

                        corecmsfood food = null;
                        if (creditsExchangeType == (int)GlobalEnumVars.CreditsExchangeType.Goods)
                            food = new corecmsfoodServices().QueryById(CommFunc.ConvertToBigInt(creditsExchange.relId));                            

                        DishItemInfo dish = new DishItemInfo();
                        dish.Name = creditsExchange.itemName.ToString();
                        dish.Money = $"{creditsExchange.amount} 积分";
                        dish.UnitName = "";
                        dish.Sign = "";
                        if (food != null)
                        {
                            dish.Name = food.name;
                            dish.UnitName = food.foodUnitName;
                        }

                        var item = new UIDishItem(dish);
                        item.Tag = creditsExchange.id.ToString();
                        item.TextName = creditsExchange.itemName;
                        item.Name = GetFoodItemName(index);
                        item.Margin = new System.Windows.Forms.Padding(3);
                        item.Click += Item_Click;
                        if (food!= null) OrderingUtil.SetDishItemImage(item, food);//加载商品图片
                        layList.Add(item);
                        index++;
                    }
                }
            }
            finally { cmd.HideOpaqueLayer(); }            
        }

        private bool CheckCouponGoods(string couponBatchId, VipCouponInfoModel vipCoupon)
        {
            if (couponBatchId == vipCoupon.couponBatchId) return false;//相同的券，只加一个就可以

            if (vipCoupon.itemWayType == (int)GlobalEnumVars.CouponItemWayType.AllGoods) return true;

            var stringList = vipCoupon.couponBatchSkuIdList;
            List<long> couponSkuId = new List<long>();
            foreach (string str in stringList)
            {
                couponSkuId.Add(CommFunc.ConvertToBigInt(str));
            }

            return true;
        }

        private void Item_Click(object sender, System.EventArgs e)
        {
            UIDishItem item = (UIDishItem)sender;
            creditsExchangeInfo = creditsExchangeList.Find(p => p.id == item.Tag.ToString());
            if (creditsExchangeInfo != null)
            {
                SetIntegralExchange();                
            }
        }

        private async void SetIntegralExchange()
        {
            string msg = string.Format("是否要兑换商品【{0}】？", creditsExchangeInfo.itemName);
            if (!ShowAskDialog(msg)) return;
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                var result = await MemberApiUtil.PostIntegralExchange(member, creditsExchangeInfo.id);
                if (result.status)
                {
                    if (creditsExchangeInfo.type == (int)GlobalEnumVars.CreditsExchangeType.Goods)
                        SaveOrderData();//保存成零售订单 

                    UIMessageBox.Show(result.msg);
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
            finally { cmd.HideOpaqueLayer();}
        }

        private void SaveOrderData()
        {
            //var orderingMaster = new corecmsfoodorderingmasterServices().GetOrderingMaster(0, AppConstVars.sysUser, AppConstVars.classId, AppConstVars.sysUser.storeId);//快餐模式
            var orderingMaster = new corecmsfoodorderingmasterServices().GreateOrderingMaster(AppConstVars.sysUser, 0, 0, 0, "", AppConstVars.classId);
            var orderingDetail = new List<corecmsfoodordering>();
            var orderPayments = new List<corecmsfoodorderpayment>();
            var orderingTag = new List<corecmsfoodorderingtag>();
            string resultStr = "";
            long foodId = CommFunc.ConvertToInt64(creditsExchangeInfo.relId);
            long specId = creditsExchangeInfo.specId;
            var ordering = ProcessUtil.CreateByFoodId(Program.frmMainWin, orderingMaster, foodId, specId, 1, member, null, ref resultStr);
            if (ordering == null)
            {
                if (!resultStr.IsNullOrEmpty()) UIMessageBox.Show(resultStr, "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                return;
            }
            //主表处理
            orderingMaster.orderNo = ProcessUtil.GetOrderNo((int)GlobalEnumVars.SerialNumberType.零售单号);
            orderingMaster.sumRealAmount = 0;
            orderingMaster.sumAllAmount = 0;
            orderingMaster.sumAllAmount1 = 0;
            orderingMaster.userId = member.id;

            //订单明细表处理
            ordering.realPrice = 0;
            ordering.realAmount = 0;
            ordering.discount = 0;
            ordering.allAmount = 0;
            orderingDetail.Add(ordering);

            //支付表处理
            corecmsfoodorderpayment posPay = new corecmsfoodorderpayment();
            posPay.id = (long)YitIdHelper.NextId();//先给付值，方便删除行
            posPay.orderId = orderingMaster.orderId;
            posPay.paymentId = 6;
            posPay.payName = "积分兑换";
            posPay.paymentCode = "pay.integral";// sysPayment.code;
            posPay.payAmount = CommFunc.ConvertToDecimal(creditsExchangeInfo.amount);
            posPay.takeAmount = CommFunc.ConvertToDecimal(creditsExchangeInfo.amount);
            posPay.status = 1;//先标记为未支付，如果移动支付等支付后改为已支付
            orderPayments.Add(posPay);

            corecmsfoodordermaster orderMaster = new corecmsfoodordermaster();
            var orderServices = new corecmsfoodordermasterServices();
            
            var bl = orderServices.SaveOrderData(AppConstVars.sysUser, orderingMaster, orderingDetail,
                orderingTag, orderPayments, AppConstVars.classId, member, ref orderMaster, ref resultStr);

            if (!bl)
            {
                UIMessageBox.Show(resultStr, "保存数据出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            new PrintServices().SetPrintSettlement(orderMaster);
        }

        /// <summary>
        /// 商品按钮名称
        /// </summary>
        /// <param name="deskId"></param>
        /// <returns></returns>
        private string GetFoodItemName(int index)
        {
            return "uiFoodItem_" + index.ToString();
        }

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void frmCouponSel_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
        {
            HideWaitForm();
        }
    }
}
